/*
 * Created by Jaren at 2022/11/27 19:12
 */
import 'dart:async';
import 'dart:io';
import 'dart:typed_data';

import 'package:inmotion_protocol/base/base_message.dart';
import 'package:inmotion_protocol/base/protocol.dart';
import 'package:inmotion_protocol/common/media_file_upload_manager.dart';
import 'package:inmotion_protocol/ezcan/file/ezcan_file_manager.dart';
import 'package:inmotion_protocol/ezcan/util.dart';
import 'package:inmotion_protocol/util/byte_util.dart';
import 'package:inmotion_protocol/util/file.dart';

class EzcanSoundFileUploadManager extends SoundFileUploadManager {
  EzcanSoundFileUploadManager(Protocol<IMessage> protocol) : super(protocol);

  @override
  Future<bool> clearCacheFiles() {
    return Future.value(true);
  }

  @override
  Future renameFileIfNeed(int id, StreamController<UploadEvent> streamController) {
    return Future.value(false);
  }

  @override
  Future<bool> checkStorageCapacityImpl(int size) {
    return Future.value(true);
  }

  @override
  MediaUploadConfig createSoundItemConfig(File localFile, int itemIndex) {
    // 由于车辆端DIY单条音效体验不好，不实现此功能
    throw UnimplementedError();
  }

  @override
  MediaUploadConfig createSoundPackConfig(File localFile, int pkgId) {
    Uint8ClampedList idBytes = ByteUtil.num2BytesLe(pkgId, 4);
    int fileSize = localFile.lengthSync();
    int sum = EzCANFileUtils.calculateFileSum(localFile, 0, fileSize - 5, idBytes);
    FileUtils.rewriteFile(localFile, fileSize - 5, ByteUtil.buildBytes(idBytes, Uint8ClampedList.fromList([sum])));

    return EzCANSoundPackFileConfig(localFile);
  }
}

class EzCANSoundPackFileConfig extends EzcanConfig with MediaUploadConfig {
  EzCANSoundPackFileConfig(File localFile) : super(localFile, EzcanConfig.typeSound);
}
